const state = {
  cart:JSON.parse(uni.getStorageSync('cart') || '[]') 
}
const mutations = {
  // 添加购物车
  ADDCART(state,goods) {
    const findResult = state.cart.find(item => item.goods_id === goods.goods_id)
    // console.log(findResult);
    if(!findResult) {
      // 没有这个商品
      state.cart.push(goods)
    }else {
      // 有这个商品 增加数量
      findResult.goods_count++
    }
    // console.log(state.cart);
    this.commit('cart/SAVESROREAGE')
  },
  // 持久化购物车
  SAVESROREAGE(state) {
    uni.setStorageSync('cart',JSON.stringify(state.cart))
  },
  // 更新购物车
  UPDATECART(state,goods) {
    state.cart.forEach(item => {
      if(item.goods_id === goods.goods_id) {
        // 判断一个对象身上是否有某个属性
        // if(goods.goods_state !== undefined) {
        if(goods.hasOwnProperty('goods_state')) {
          // 更新商品是否勾选
          item.goods_state = goods.goods_state
        }else if(goods.goods_count !== undefined) {
          // 更新商品数量
          item.goods_count = goods.goods_count
        }
      }
    })
    // 更新到本地
    this.commit('cart/SAVESROREAGE')
  },
  // 删除购物车
  DELETECART(state,goods) {
    state.cart = state.cart.filter(item => item.goods_id !== goods.goods_id)
    // 更新到本地
    this.commit('cart/SAVESROREAGE')
  },
  // 全选影响每个选项
  UPDATEALL(state,allState) {
    state.cart.forEach(item => {
      item.goods_state = allState
    })
    // 更新到本地
    this.commit('cart/SAVESROREAGE')
  }
}
const actions = {}
const getters = {
  // 所有选中的商品数量
  goodsStateCount(state) {
  return  state.cart.filter(item => item.goods_state).reduce((total,item) => total += item.goods_count,0)
  },
  // 全选的状态
  isAll(state) {
    return state.cart.every(item => item.goods_state)
  },
  // 勾选商品的总价格
  priceAll(state) {
   return state.cart.filter(item => item.goods_state).reduce((total,obj) => total += (obj.goods_price * obj.goods_count),0).toFixed(2)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
